import React, { useState, useEffect } from "react";
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  Select,
  message,
  Popconfirm,
  Switch,
  Upload,
  Image,
} from "antd";
import { PlusOutlined } from "@ant-design/icons";
import MarkdownIt from "markdown-it";
import MdEditor from "react-markdown-editor-lite";
import "react-markdown-editor-lite/lib/index.css";
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";
import {
  getArticleList,
  addArticle,
  deleteArticle,
  updateArticle,
  getArticleContent,
  uploadImage,
} from "../../api/article";

const { Option } = Select;
const { TextArea } = Input;

// 创建 Markdown 解析器实例
const mdParser = new MarkdownIt();

const ArticleManagement = () => {
  // 状态定义
  const [articles, setArticles] = useState([]); // 文章列表
  const [isModalOpen, setIsModalOpen] = useState(false); // 控制模态框显示
  const [isViewModalOpen, setIsViewModalOpen] = useState(false); // 控制查看模态框显示
  const [editingArticle, setEditingArticle] = useState(null); // 当前编辑的文章
  const [viewingArticle, setViewingArticle] = useState(null); // 当前查看的文章
  const [form] = Form.useForm(); // 创建表单实例
  const [isLoading, setIsLoading] = useState(false); // 加载状态
  const [contentType, setContentType] = useState("markdown"); // 内容类型状态

  // 组件挂载时获取文章列表
  useEffect(() => {
    fetchArticles();
  }, []);

  // 获取文章列表
  const fetchArticles = async () => {
    setIsLoading(true);
    try {
      const response = await getArticleList();
      setArticles(response.data);
    } catch (error) {
      message.error("获取文章列表失败");
    }
    setIsLoading(false);
  };

  // 显示模态框
  const showModal = async (article = null) => {
    setEditingArticle(article);
    if (article) {
      try {
        const response = await getArticleContent(article.id);
        if (response.code === 0 && response.data) {
          const fullArticle = response.data;
          let images = [];
          try {
            images = JSON.parse(fullArticle.images || "[]");
          } catch (e) {
            console.error("Error parsing images:", e);
          }
          form.setFieldsValue({
            ...fullArticle,
            contentType: fullArticle.contentType,
            images: images.map((url) => ({ url, uid: url })),
          });
          setContentType(fullArticle.contentType);
        } else {
          throw new Error(response.message || "获取文章内容失败");
        }
      } catch (error) {
        console.error("Error fetching article content:", error);
        message.error("获取文章内容失败");
        return;
      }
    } else {
      form.resetFields();
      setContentType("markdown");
    }
    setIsModalOpen(true);
  };

  // 显示查看模态框
  const showViewModal = async (article) => {
    try {
      const response = await getArticleContent(article.id);
      if (response.code === 0 && response.data) {
        const fullArticle = response.data;
        fullArticle.images = fullArticle.images
          ? JSON.parse(fullArticle.images)
          : [];
        setViewingArticle(fullArticle);
        setIsViewModalOpen(true);
      } else {
        throw new Error(response.message || "获取文章内容失败");
      }
    } catch (error) {
      console.error("Error fetching article content:", error);
      message.error("获取文章内容失败");
    }
  };

  // 关闭编辑模态框
  const handleCancel = () => {
    setIsModalOpen(false);
    setEditingArticle(null);
    form.resetFields();
  };

  // 关闭查看模态框
  const handleViewCancel = () => {
    setIsViewModalOpen(false);
    setViewingArticle(null);
  };

  // 提交表单
  const handleSubmit = async (values) => {
    try {
      const submittingValues = {
        ...values,
        contentType,
        images: values.images
          ? JSON.stringify(values.images.map((img) => img.url))
          : null, // 只保存 URL
      };
      if (editingArticle) {
        await updateArticle(editingArticle.id, submittingValues);
        message.success("更新文章成功");
      } else {
        await addArticle(submittingValues);
        message.success("添加文章成功");
      }
      setIsModalOpen(false);
      form.resetFields();
      fetchArticles();
    } catch (error) {
      message.error("操作失败");
    }
  };

  // 删除文章
  const handleDelete = async (id) => {
    try {
      await deleteArticle(id);
      message.success("删除文章成功");
      fetchArticles();
    } catch (error) {
      message.error("删除文章失败");
    }
  };

  // 处理编辑器内容变化
  const handleEditorChange = ({ text }) => {
    form.setFieldsValue({ content: text });
  };

  // 处理内容类型变化
  const handleContentTypeChange = (value) => {
    setContentType(value);
    form.setFieldsValue({ contentType: value });
  };

  // 处理图片上传
  const handleUpload = async (options) => {
    const { onSuccess, onError, file } = options;
    try {
      const result = await uploadImage(file);
      console.log(result);
      if (result.code === 0) {
        const imageUrl = result.data.url;
        message.success("图片上传成功");
        onSuccess({ url: imageUrl, uid: imageUrl });

        // 更新表单中的 images 字段
        const currentImages = form.getFieldValue("images") || [];
        console.log("表中字段", currentImages);
        form.setFieldsValue({
          images: [...currentImages, { url: imageUrl, uid: imageUrl }],
        });
      } else {
        onError(new Error(result.message || "上传失败"));
      }
    } catch (err) {
      console.error("Upload error:", err);
      onError(new Error("上传失败"));
    }
  };

  // 表格列定义
  const columns = [
    { title: "标题", dataIndex: "title", key: "title" },
    { title: "类型", dataIndex: "type", key: "type" },
    { title: "创建时间", dataIndex: "createTime", key: "createTime" },
    { title: "更新时间", dataIndex: "updateTime", key: "updateTime" },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status) => (status === 1 ? "启用" : "禁用"),
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <span>
          <Button type="link" onClick={() => showViewModal(record)}>
            查看
          </Button>
          <Button type="link" onClick={() => showModal(record)}>
            编辑
          </Button>
          <Popconfirm
            title="确定要删除此文章吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link">删除</Button>
          </Popconfirm>
        </span>
      ),
    },
  ];

  return (
    <div>
      <Button
        type="primary"
        onClick={() => showModal()}
        style={{ marginBottom: 16 }}
      >
        新增文章
      </Button>
      <Table
        columns={columns}
        dataSource={articles}
        rowKey="id"
        loading={isLoading}
      />
      <Modal
        title={editingArticle ? "编辑文章" : "新增文章"}
        open={isModalOpen}
        onCancel={handleCancel}
        footer={null}
        width={800}
      >
        {isModalOpen && (
          <Form form={form} onFinish={handleSubmit} layout="vertical">
            <Form.Item
              name="title"
              label="标题"
              rules={[{ required: true, message: "请输入标题" }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="type"
              label="类型"
              rules={[{ required: true, message: "请选择类型" }]}
            >
              <Select>
                <Option value="JavaScript">JavaScript</Option>
                <Option value="Html">Html</Option>
                <Option value="css">css</Option>
                <Option value="Vue">Vue</Option>
                <Option value="React">React</Option>
              </Select>
            </Form.Item>
            <Form.Item name="keywords" label="关键字">
              <Input />
            </Form.Item>
            <Form.Item name="summary" label="摘要">
              <TextArea rows={4} />
            </Form.Item>
            <Form.Item name="contentType" label="内容类型">
              <Select value={contentType} onChange={handleContentTypeChange}>
                <Option value="markdown">Markdown</Option>
                <Option value="richtext">富文本</Option>
              </Select>
            </Form.Item>
            <Form.Item
              name="content"
              label="内容"
              rules={[{ required: true, message: "请输入内容" }]}
            >
              {contentType === "markdown" ? (
                <MdEditor
                  style={{ height: "400px" }}
                  renderHTML={(text) => mdParser.render(text)}
                  onChange={handleEditorChange}
                  value={form.getFieldValue("content") || ""}
                />
              ) : (
                <ReactQuill theme="snow" style={{ height: "300px" }} />
              )}
            </Form.Item>
            <Form.Item name="images" label="组图">
              <Upload
                listType="picture-card"
                fileList={form.getFieldValue("images") || []}
                onChange={({ fileList }) => {
                  form.setFieldsValue({ images: fileList });
                }}
                customRequest={handleUpload}
              >
                <div>
                  <PlusOutlined />
                  <div style={{ marginTop: 8 }}>上传</div>
                </div>
              </Upload>
            </Form.Item>
            <Form.Item name="status" label="状态" valuePropName="checked">
              <Switch />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                {editingArticle ? "更新" : "添加"}
              </Button>
            </Form.Item>
          </Form>
        )}
      </Modal>
      <Modal
        title="查看文章"
        open={isViewModalOpen}
        onCancel={handleViewCancel}
        footer={null}
        width={800}
      >
        {viewingArticle && (
          <div>
            <h2>{viewingArticle.title}</h2>
            <p>类型: {viewingArticle.type}</p>
            <p>关键字: {viewingArticle.keywords}</p>
            <p>摘要: {viewingArticle.summary}</p>
            <div>
              内容:
              {viewingArticle.contentType === "markdown" ? (
                <div
                  dangerouslySetInnerHTML={{
                    __html: mdParser.render(viewingArticle.content),
                  }}
                />
              ) : (
                <div
                  dangerouslySetInnerHTML={{ __html: viewingArticle.content }}
                />
              )}
            </div>
            <div>
              组图:
              {viewingArticle.images && viewingArticle.images.length > 0 && (
                <Image.PreviewGroup>
                  {viewingArticle.images.map((imageUrl, index) => (
                    <Image key={index} width={200} src={imageUrl} />
                  ))}
                </Image.PreviewGroup>
              )}
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default ArticleManagement;
